package com.lixiaoyao.reggie.controller;

import com.lixiaoyao.reggie.entity.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
    @Value("${reggie.path}")
    private String basePath;
    @PostMapping("/upload")
    public R<String> upload(@RequestParam("file") MultipartFile file1){
        log.info(file1.toString());

        String originalFilename = file1.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        String uuid = UUID.randomUUID().toString()+substring;
        //判断目录是否存在,不存在则创建目录
        File dir = new File(basePath);
        if(!dir.exists()){
            dir.mkdirs();
        }
        try {
            file1.transferTo(new File(basePath+uuid));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return R.success(uuid);
    }
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        log.info(name.toString());

        try {
            //使用输入流读取图片信息
            File file = new File(basePath + name);
            FileInputStream fileInputStream = new FileInputStream(file);
            //使用输出流返回图片信息
            ServletOutputStream outputStream = response.getOutputStream();
            //设置返回值类型
            response.setContentType("image/jpeg");
            //创建byte数组用来接收输入流读取到的数据
            byte[] bytes = new byte[1024];
            //创建一个变量用来存储读取到的有效数据长度
            int len = 0;
            while ((len=fileInputStream.read(bytes))!=-1){{
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }}
            fileInputStream.close();
            outputStream.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
